/**
 * 用户信息状态数据
 */
import cookies from 'js-cookies'
import { 
   REGISTER_OK, LOGIN_OK, UPDATA_USER_INFO, EXIT_LOGIN,
   USE_COOKIE_GET_USERINFO
} from './action-type'

const initState = JSON.parse(window.sessionStorage.getItem('user'))
function userReducer(state = initState, action) {
   switch(action.type) {
      case REGISTER_OK:
         // 注册成功
         state = action.data
         window.sessionStorage.setItem('user', JSON.stringify(state))
         return state
      case LOGIN_OK:
         // 登录成功
         state = action.data
         window.sessionStorage.setItem('user', JSON.stringify(state))
         return state
      case UPDATA_USER_INFO:
         // 更新用户信息
         state = { ...state, ...action.data }
         window.sessionStorage.setItem('user', JSON.stringify(state))
         return state
      case EXIT_LOGIN:
         // 退出登陆清除用户数据
         state = action.data
         cookies.removeItem('userid')
         window.sessionStorage.removeItem('user')
         return {}
      case USE_COOKIE_GET_USERINFO:
         // 根据cookie实现自动登录
         state = action.data
         window.sessionStorage.setItem('user', JSON.stringify(state))
         return state
      default :
         return state
   }
}
export default userReducer